<?php

declare(strict_types=1);

namespace app\system\controller;

use app\admin\BaseAdminController;
use think\facade\View;
use app\system\model\Dept;
use think\facade\Request;
use app\admin\model\Admin;
use app\system\model\LogOperate as Log;
use app\system\model\Role;
use app\system\model\Post;
use app\admin\model\Data;

class User extends BaseAdminController
{
    /**
     * 成员管理页面
     */
    public function index()
    {
        View::assign('title', '用户管理/系统管理');
        $tree = Dept::where('status', 0)->order(['sort' => 'asc', 'id' => 'desc'])->select();
        View::assign('tree', json_encode(generateTree($tree), 256));
        View::assign('options', generateOptions($tree));
        View::assign('role', Role::where('status', 0)->column('name', 'id'));
        View::assign('jobs', Post::where('status', 0)->column('name', 'id'));
        View::assign('addJs', addJs(['datepicker', 'jstree']));
        return View::fetch();
    }

    /**
     * 保存成员信息
     */
    public function save()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = input('id/d', 0);
        $pid = input('pid/d', 0);
        $username = input('username');
        $nickname = input('nickname');
        $phone = input('phone');
        $password = input('password');
        $job = input('job/d', 0);
        $role = input('role/d', 0);
        if ($id) {
            $obj = Admin::find($id);
            $obj->username = $username;
            $obj->nickname = $nickname;
            $obj->phone = $phone;
            $obj->dept_id = $pid;
            $obj->job_id = $job;
            $obj->role_id = $role;
            if ($password) {
                $obj->password = password_hash($password, PASSWORD_DEFAULT);
            }
            $obj->save();
            $title = '编辑用户';
        } else {
            if (empty($password)) {
                return json(['msg' => '密码不能为空']);
            }
            $obj = new Admin();
            $obj->username = $username;
            $obj->nickname = $nickname;
            $obj->phone = $phone;
            $obj->dept_id = $pid;
            $obj->job_id = $job;
            $obj->role_id = $role;
            $obj->password = password_hash($password, PASSWORD_DEFAULT);
            $obj->save();
            $title = '新增用户';
        }
        $dept = Dept::column('name', 'id');
        $roles = Role::column('name', 'id');
        $jobs = Post::column('name', 'id');
        Log::add($title, [
            'ID' => $obj->id,
            '登录账户' => $username,
            '昵称' => $nickname,
            '手机' => $phone,
            '部门' => $dept[$pid] ?? '-',
            '角色' => $roles[$role] ?? '-',
            '岗位' => $jobs[$job] ?? '-'
        ]);
        return json(['msg' => '']);
    }

    /**
     * 导出成员信息
     */
    public function export()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        [$obj,] = $this->_();
        $list = $obj->order('id', 'desc')->select();
        $data = [];
        foreach ($list as $value) {
            $data[] = [
                'ID' => $value['id'],
                '账户' => $value['username'],
                '部门' => $value['dept'] ? $value['dept']['name'] : '-',
                '昵称' => $value['nickname'],
                '手机号码' => $value['phone'],
                '创建时间' => $value['create_time'],
            ];
        }
        $url = Data::export('成员数据', $data);
        $get = Request::get();
        $get['excel'] = explode('=', $url)[1];
        Log::add('导出成员数据', $get);
        return json(['url' => $url]);
    }

    /**
     * 查询成员信息
     */
    private function _()
    {
        $dept_id = input('dept_id/d');
        $nickname = input('nickname');
        $phone = input('phone');
        $status = input('status/d');
        $start = input('start');
        $end = input('end');
        $obj = new Admin();
        if ($nickname) {
            $obj = $obj->where('nickname', 'like', '%' . trim($nickname) . '%');
        }
        if ($phone) {
            $obj = $obj->where('phone', 'like', '%' . trim($phone) . '%');
        }
        if ($status) {
            $obj = $obj->where('status', $status - 1);
        }
        if ($start) {
            $obj = $obj->where('create_time', '>=', strtotime($start . ' 00:00:00'));
        }
        if ($end) {
            $obj = $obj->where('create_time', '<=', strtotime($end . ' 23:59:59'));
        }
        if ($dept_id) {
            $obj = $obj->where('dept_id', 'in', Dept::getDeptId($dept_id));
        }
        $total = $obj->count();
        $obj = $obj->with(['dept' => function ($query) {
            $query->withTrashed();
            $query->field(['id', 'name']);
        }]);
        return [$obj, $total];
    }

    /**
     * 读取成员信息列表
     */
    public function data()
    {
        $offset = input('offset/d');
        $limit = input('limit/d');
        [$obj, $total] = $this->_();
        $list = $obj->order('id', 'asc')->limit($offset, $limit)->select();
        return json([
            'total' => $total,
            'rows' => $list,
        ]);
    }

    /**
     * 成员状态变更
     */
    public function status()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = input('id/d', 0);
        $obj = Admin::find($id);
        $status = $obj->status ? '正常' : '停用';
        $obj->status = $obj->status ? 0 : 1;
        $obj->save();
        Log::add('成员状态', [
            'ID' => $id,
            '登录账号' => $obj->username,
            '昵称' => $obj->nickname,
            '手机号码' => $obj->phone,
            '状态' => $status,
        ]);
        return json(['msg' => '']);
    }

    /**
     * 设置后台可登录状态
     */
    public function login()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = input('id/d', 0);
        $obj = Admin::find($id);
        $status = $obj->login ? '允许登录后台' : '禁止登录后台';
        $obj->login = $obj->login ? 0 : 1;
        $obj->save();
        Log::add('后台访问设置', [
            'ID' => $id,
            '登录账号' => $obj->username,
            '昵称' => $obj->nickname,
            '手机号码' => $obj->phone,
            '状态' => $status,
        ]);
        return json(['msg' => '']);
    }

    /**
     * 查看成员信息
     */
    public function view()
    {
        $id = input('id/d', 0);
        $obj = Admin::find($id);
        return json($obj);
    }

    /**
     * 删除成员信息
     */
    public function remove()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $id = input('id/d', 0);
        $obj = Admin::find($id);
        $obj->delete();
        Log::add('删除用户', [
            'ID' => $id,
            '登录账号' => $obj->username,
            '昵称' => $obj->nickname,
            '手机号码' => $obj->phone,
        ]);
        return json(['msg' => '']);
    }
}
